package com.zpark.rabbitmq.route;

import com.rabbitmq.client.*;
import com.zpark.rabbitmq.config.ConnectionUtil;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @PackageName: com.zpark.rabbitmq.route
 * @ClassName: Consumer2
 * @Description:
 * @author: RZS
 * @date: 2022/12/13  17:09
 */
public class Consumer2 {

    // 定义队列名字
    private static final String QUEUE_NAME = "test_queue_d2";
    // 定义交换机名字
    private static final String EXCHANGE_NAME = "test_exchange_direct";

    public static void main(String[] args) throws IOException, TimeoutException {
        // 获取连接
        Connection conn = ConnectionUtil.getConnection();
        // 获取通道
        final Channel channel = conn.createChannel();
        // 声明交换机
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
        // 声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        // 路由key与队列和交换机绑定
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "delete");
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "update");
        channel.basicQos(1);
        channel.basicConsume(QUEUE_NAME, false, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "utf-8");
                System.out.println("消费者2，消费 msg " + msg);
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });
    }
}
